import json
from django.http import JsonResponse
from django.shortcuts import render, redirect, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from app01.utils.form import TaskModelForm
from app01 import models
from app01.utils.pagination import Pagination

def task_list(request):
    """任务列表"""
    #去数据库获取所有的任务
    queryset = models.Task.objects.all().order_by('-id')
    form = TaskModelForm()
    page_object = Pagination(request, queryset)
    # 参数字典
    context = {
        "form":form,
        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html(),  # 生成的页码
    }
    return render(request, "task_list.html", context)


@csrf_exempt
def task_ajax(request):
    print(request.GET)
    print(request.POST)
    data_dict = {
        "status": True,
        "data": [1, 2, 3, 4]
    }
    json_string = json.dumps(data_dict)
    return HttpResponse(json_string)


@csrf_exempt
def task_add(request):
    """添加任务"""
    #print(request.POST)
    # <QueryDict: {'level': ['1'], 'title': ['111'], 'detail': ['11'], 'user': ['1']}>
    # 1、对用户发送的数据表单进行校验（此处使用ModelForm进行校验）
    form = TaskModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        data_dict = {"status": True}
        return JsonResponse(data_dict)
    data_dict = {
        "status": False,
        "error": form.errors
    }
    return JsonResponse(data_dict)
